import React, { useEffect, useState } from 'react'
import { Button, Card, Drawer, Form, Input, message, Modal, Tabs, Tag } from 'antd';
import styles from './style.less'
import { getList, addQuestions, deleteQuestions, editQuestions, addRunCase, runCase, checkCase } from './service'
import ProTable from '@ant-design/pro-table';
import MPageContainer from '@/components/MPageContainer';
import qs from 'qs'
import { PlusOutlined } from '@ant-design/icons';

const Question: React.FC = () => {

    const [addQuestionVisvible, setAddQuestionVisvible] = useState(false)
    const [type, setType] = useState<any>('1')
    const [list1, setList1] = useState()
    const [list2, setList2] = useState()
    const [list3, setList3] = useState()
    const [list4, setList4] = useState()
    const [isAdd, setIsAdd] = useState<any>(false)
    const [questionId, setQuestionId] = useState()
    const [isProgram, setIsProgram] = useState(false)
    const [runVisvible, setRunVisvible] = useState(false)
    const [codeQuestionId, setCodeQuestionId] = useState()
    const [codeAnswer, setCodeAnswer] = useState()
    const [input, setInput] = useState()

    const { TabPane } = Tabs;
    const { TextArea } = Input;

    const { Item } = Form;
    const [questionForm] = Form.useForm();
    const [runForm] = Form.useForm();


    const formLayout = {
        labelCol: { span: 4 },
        wrapperCol: { span: 18 },
    };

    const onChange = (key: any) => {
        setType(key)
    }

    const addQuestion = () => {
        if (type !== '1') {
            setIsAdd(true)
            setAddQuestionVisvible(true)
        }
    }

    const codeAddQuestion = () => {
        setIsProgram(true)
        setAddQuestionVisvible(true)
    }

    const getLists = async () => {
        const res1 = await getList(1);
        const res2 = await getList(2);
        const res3 = await getList(3);
        const res4 = await getList(4);
        setList1(res1.data)
        setList2(res2.data)
        setList3(res3.data)
        setList4(res4.data)
        const data1 = res1.data.map((item: any) => { return { questionId: item.questionId, title: JSON.parse(item.content).title } })
        const data2 = res2.data.map((item: any) => { return { questionId: item.questionId, title: JSON.parse(item.content).title } })
        const data3 = res3.data.map((item: any) => { return { questionId: item.questionId, title: JSON.parse(item.content).title } })
        const data4 = res4.data.map((item: any) => { return { questionId: item.questionId, title: JSON.parse(item.content).title } })
        localStorage.setItem('1', JSON.stringify(data1))
        localStorage.setItem('2', JSON.stringify(data2))
        localStorage.setItem('3', JSON.stringify(data3))
        localStorage.setItem('4', JSON.stringify(data4))
    }

    const deleteQuestion = async (id: any) => {
        const res = await deleteQuestions(id);
        console.log(res, 'resres');
        if (res.code === 200) {
            message.success('删除成功')
            getLists()
        }
    }

    const editQuestion = async (id: any) => {
        setAddQuestionVisvible(true)
        setQuestionId(id)
    }

    useEffect(() => {
        getLists()
    }, [])

    const columns = [
        {
            title: '题目title',
            dataIndex: 'content',
            render: (_: any, record: any) => {
                const content = JSON.parse(record.content)
                return <pre>{content.title}</pre>
            }
        },
        {
            title: '题目body',
            dataIndex: 'content',
            render: (_: any, record: any) => {
                const content = JSON.parse(record.content)
                return <pre>{content.body}</pre>
            }
        },
        {
            title: '题目example',
            dataIndex: 'content',
            render: (_: any, record: any) => {
                const content = JSON.parse(record.content)
                return <pre>{content.example}</pre>
            }
        },
        {
            title: '题目options',
            dataIndex: 'content',
            render: (_: any, record: any) => {
                const content = JSON.parse(record.content)
                return <>{content.options?.map((item: any, index: any) => {
                    return <li className={styles.tag}> <Tag color={'blue'}>{item !== '' ? `${index == 0 ? 'A' : index == 1 ? 'B' : index == 2 ? 'C' : 'D'}、${item}` : ''}</Tag></li>
                })}</>

            }
        },
        {
            title: '题目answer',
            dataIndex: 'answer',
            render: (_: any, record: any) => {
                return <pre>{record.answer}</pre>
            }
        },
        {
            title: '操作',
            width: 180,
            render: (_: any, record: any) => {
                return <>
                    {record.type === 1 ? '' : <Tag color={'blue'} onClick={() => { editQuestion(record.questionId) }} className={styles.classTag}>编辑问题</Tag>}
                    <Tag color={'red'} onClick={() => { deleteQuestion(record.questionId) }} className={styles.classTag}>删除问题</Tag>
                </>
            }
        },
    ]

    const handleAddQuestionOk = async () => {
        setAddQuestionVisvible(false)
        const fieldsValue = await questionForm.validateFields();
        const options = fieldsValue.options?.split('，');
        const answer = fieldsValue.answer;
        const content = {
            ...fieldsValue,
            options: options
        }
        delete content.answer;
        const obj = {
            content: JSON.stringify(content),
            answer: answer,
            type: parseInt(type),
            questionId: questionId
        }
        if (isAdd) {
            const res = await addQuestions(qs.stringify(obj))
            if (res.code === 200) {
                message.success('添加成功');
                getLists()
            }
            console.log(res, 'res');
        } else {
            const res = await editQuestions(qs.stringify(obj))
            if (res.code === 200) {
                message.success('修改成功');
                getLists()
            }
            console.log(res, 'resresres');
        }
    }

    const handleAddQuestionCancel = () => {
        setAddQuestionVisvible(false)
    }

    // 运行用例
    const handleAddProgramOk = async () => {
        setIsProgram(false)
        const fieldsValue = await questionForm.validateFields();
        const options = fieldsValue.options?.split('，');
        const answer = fieldsValue.answer;
        setCodeAnswer(answer)
        const content = {
            ...fieldsValue,
            options: options
        }
        delete content.answer;
        const obj = {
            content: JSON.stringify(content),
            answer: answer,
            type: parseInt(type),
            questionId: questionId
        }
        const res = await addQuestions(qs.stringify(obj))
        console.log(res, 'ressssss');

        if (res.code === 200) {
            // message.success('添加成功');
            // getLists()
            setRunVisvible(true)
            setAddQuestionVisvible(false)
            setCodeQuestionId(res.data.questionId)
        }
    }

    const handleRunCancel = () => {
        setIsProgram(false)
        setRunVisvible(false)
    }

    const run = async () => {
        const obj = {
            questionId: codeQuestionId,
            code: codeAnswer
        }
        const ress = await runCase(qs.stringify(obj))
        if (ress.code === 300) {
            setTimeout(() => {
                run()
            }, 1000)
        }
        else if (ress.code === 200) {
            const resss = await checkCase(ress.data.codeId)
            if (resss.code === 200) {
                const objj = {
                    questionId: codeQuestionId,
                    casesStr: JSON.stringify([{ standardOutput: resss.data[0]?.codeOutput, standardInput: input }])
                }
                const ressss = await addRunCase(qs.stringify(objj))
                if (ressss.code === 200) {
                    message.success('添加编程题成功')
                }
            }
        }
    }

    const handleRunProgramOk = async () => {
        const fieldsValue = await runForm.validateFields();
        console.log(fieldsValue, 'fieldsValuefieldsValue');
        const input = fieldsValue.input.split('\n');
        setInput(input)

        const obj = {
            questionId: codeQuestionId,
            casesStr: JSON.stringify([{ standardOutput: [], standardInput: input }])
        }
        const res = await addRunCase(qs.stringify(obj))
        if (res.code === 200) {
            run()
        }
        setIsProgram(false)
        setRunVisvible(false)
    }


    return (
        <>
            {/* <MPageContainer> */}
            <Card className={styles.card}>
                <Tabs defaultActiveKey="1" centered onChange={onChange}>
                    <TabPane tab="编程题" key="1">
                        <ProTable
                            headerTitle={<div className={styles.tags}><Tag color={'blue'}>编程题</Tag></div>}
                            columns={columns as never[]}
                            dataSource={list1}
                            toolBarRender={() => [
                                <Button key="button" icon={<PlusOutlined />} type="primary" onClick={() => { codeAddQuestion() }}>
                                    添加题目
                            </Button>
                            ]}
                            search={false}
                            rowKey="classId"
                            pagination={{
                                showQuickJumper: true,
                            }}
                        />
                    </TabPane>
                    <TabPane tab="判断题" key="2">
                        <ProTable
                            headerTitle={<div className={styles.tags}><Tag color={'blue'}>判断题</Tag></div>}
                            columns={columns as never[]}
                            dataSource={list2}
                            toolBarRender={() => [
                                <Button key="button" icon={<PlusOutlined />} type="primary" onClick={() => { addQuestion() }}>
                                    添加题目
                            </Button>
                            ]}
                            search={false}
                            rowKey="classId"
                            pagination={{
                                showQuickJumper: true,
                            }}
                        />
                    </TabPane>
                    <TabPane tab="选择题" key="3">
                        <ProTable
                            headerTitle={<div className={styles.tags}><Tag color={'blue'}>选择题</Tag></div>}
                            columns={columns as never[]}
                            dataSource={list3}
                            toolBarRender={() => [
                                <Button key="button" icon={<PlusOutlined />} type="primary" onClick={() => { addQuestion() }}>
                                    添加题目
                            </Button>
                            ]}
                            search={false}
                            rowKey="classId"
                            pagination={{
                                showQuickJumper: true,
                            }}
                        />
                    </TabPane>
                    <TabPane tab="填空题" key="4">
                        <ProTable
                            headerTitle={<div className={styles.tags}><Tag color={'blue'}>填空题</Tag></div>}
                            columns={columns as never[]}
                            dataSource={list4}
                            toolBarRender={() => [
                                <Button key="button" icon={<PlusOutlined />} type="primary" onClick={() => { addQuestion() }}>
                                    添加题目
                            </Button>
                            ]}
                            search={false}
                            rowKey="classId"
                            pagination={{
                                showQuickJumper: true,
                            }}
                        />
                    </TabPane>
                </Tabs>
            </Card>
            {/* </MPageContainer> */}
            {
                <Modal title={isAdd ? '添加问题' : '编辑题目'} visible={addQuestionVisvible} onOk={isProgram ? handleAddProgramOk : handleAddQuestionOk} onCancel={handleAddQuestionCancel}>
                    <Form
                        {...formLayout}
                        form={questionForm}
                    >
                        <Item name="title" rules={[{ required: true }]} label="title">
                            <Input size="large" placeholder="请输入title" />
                        </Item>
                        <Item name="body" rules={[{ required: true }]} label="body">
                            <TextArea size="large" placeholder="请输入body" />
                        </Item>
                        <Item name="example" rules={[{ required: true }]} label="example">
                            <Input size="large" placeholder="请输入example" />
                        </Item>
                        <Item name="options" rules={[{ required: true }]} label="options">
                            <Input size="large" placeholder="请输入options,选项用 “，” 分割" />
                        </Item>
                        <Item name="others" rules={[{ required: true }]} label="others">
                            <Input size="large" placeholder="请输入others" />
                        </Item>
                        <Item name="answer" rules={[{ required: true }]} label="answer">
                            <TextArea size="large" placeholder="请输入answer" />
                        </Item>
                    </Form>
                </Modal>
            }
            {
                <Modal title={'运行用例'} visible={runVisvible} onOk={handleRunProgramOk} onCancel={handleRunCancel}>
                    <Form
                        {...formLayout}
                        form={runForm}
                    >
                        <Item name="input" label="输入用例">
                            <TextArea size="large" placeholder="请输入输入用例" />
                        </Item>
                    </Form>
                </Modal>
            }
        </>
    );
}

export default Question;

